package com.xiaoyu.lanling.feature.mission.activity

import `in`.srain.cube.views.list.CubeRecyclerViewSimpleAdapter
import android.os.Bundle
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.activity.base.AppCompatToolbarActivity
import com.xiaoyu.lanling.event.checkin.CheckInEvent
import com.xiaoyu.lanling.event.task.MissionListEvent
import com.xiaoyu.lanling.feature.mission.data.MissionData
import com.xiaoyu.lanling.feature.mission.model.MissionBaseItem
import com.xiaoyu.lanling.feature.mission.viewholder.MissionViewHolderManager
import com.xiaoyu.lanling.router.Router
import kotlinx.android.synthetic.main.activity_mission.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MissionListActivity : AppCompatToolbarActivity() {

    private val requestTag = Any()
    private val missionData = MissionData()

    private val adapter = CubeRecyclerViewSimpleAdapter<MissionBaseItem>()

    override fun onCreateSafelyAfterAppFinishInit(savedInstanceState: Bundle?) {
        super.onCreateSafelyAfterAppFinishInit(savedInstanceState)
        setLightStatusBar()
        setContentView(R.layout.activity_mission)
        initToolbar()

        initView()
        initBind()
        initAdapter()
        initEvent()
    }

    private fun initBind() {
        invite_banner.setOnClickListener { Router.instance.gotoInviteActivity(this) }
    }

    override fun onStartSafelyAfterAppFinishInit(isFirstTimeStart: Boolean) {
        super.onStartSafelyAfterAppFinishInit(isFirstTimeStart)
        initData()
    }

    private fun initView() {
        title = getString(R.string.task_title)
    }

    private fun initAdapter() {
        MissionViewHolderManager.bindViewHolder(adapter)
        recyclerview.adapter = adapter
    }

    private fun initEvent() {
        AppEventBus.bindContainerAndHandler(this, object : SimpleEventHandler() {
            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: MissionListEvent) {
                if (event.isNotFromThisRequestTag(requestTag)) {
                    return
                }
                showData(event)
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: CheckInEvent) {
                initData()
            }
        })
    }

    private fun showData(event: MissionListEvent) {
        adapter.list = event.list
        adapter.notifyDataSetChanged()
    }

    private fun initData() {
        missionData.getMissionList(requestTag)
    }
}